package com.topnav.mc.schedule;


import java.util.Map;

import com.topnav.mc.schedule.task.QuartzTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
/**
 *
 * @类名: JobManagement
 * @说明: 任务调度管理器
 *
 * @author: kenny
 * @Date	2022年1月26日上午9:51:17
 * 修改记录：
 *  动态管理可参考：https://www.cnblogs.com/yzuzhang/articles/5728621.html
 * @see
 */
@Service
@Slf4j
public class JobManagement {
    @Autowired
    private Scheduler scheduler;

    /**
     * 添加一个定时任务 QuartzTask
     * @param task
     */
    public void addJob(QuartzTask task){
        addJob(task.getJobName(),task.getJobGroupName(),task.getTriggerName(),task.getTriggerGroupName(),
                task.getJobClass(),task.getCron(),task.getParams());
    }

    /**
     * 添加一个定时任务
     * @param jobName			任务名
     * @param jobGroupName      任务组名
     * @param triggerName       触发器名
     * @param triggerGroupName  触发器组名
     * @param jobClass          任务
     * @param cron              时间设置，参考quartz说明文档
     * @param params            参数
     */
    public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName,
                       String jobClass, String cron, Map<String, Object> params) {
        try {
            Class<? extends Job> aClass = (Class<? extends Job>) Class.forName(jobClass).newInstance().getClass();
            // 任务名，任务组，任务执行类
            JobDetail job = JobBuilder.newJob(aClass).withIdentity(jobName, jobGroupName).build();
            // 任务参数
            job.getJobDataMap().putAll(params);

            // 触发器
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();

            // 调度容器设置JobDetail和Trigger
            scheduler.scheduleJob(job, trigger);


        } catch (Exception e) {
            log.error("错误：{}",e.toString());
            throw new RuntimeException(e);

        }
    }



    /**
     * 开始执行所有任务
     * @throws SchedulerException
     */
    public void start() throws SchedulerException {
/*        // 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class).withIdentity("job1", "group1").build();
        // 基于表达式构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job1", "group1")
                .withSchedule(cronScheduleBuilder).build();
        scheduler.scheduleJob(jobDetail, cronTrigger);
        // 启动
*/
        if (!scheduler.isShutdown()) {
            scheduler.start();
        }
    }

    /**
     * 暂停定时任务
     * @param task
     * @return
     */
    public boolean stopTask(QuartzTask task){
        return stopTask(task.getJobName(),task.getJobGroupName());
    }
    /**
     * 暂停定时任务
     * @param jobName 定时任务class路径
     * @param jobGroupName 定时任务组名
     * @return
     */
    public boolean stopTask(String jobName,String jobGroupName){
        try {
            JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            log.error("获取Scheduler失败 ",e);
            return false;
        }
        return true;
    }
    /**
     * 暂停所有任务
     * @return
     */
    public  boolean stopAll(){
        try {
            scheduler.pauseAll();
        } catch (SchedulerException e) {
            log.error("获取Scheduler失败 ",e);
            return false;
        }
        return true;
    }
    /**
     * 恢复定时任务
     * @param jobName 定时任务class路径
     * @param jobGroupName 定时任务组名
     * @return
     */
    public boolean resumeTask(String jobName,String jobGroupName){
        try {
            JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            log.error("获取Scheduler失败 ",e);
            return false;
        }
        return true;
    }
    /**
     * 恢复所有任务
     * @return
     */
    public boolean resumeAll(){
        try {
            scheduler.resumeAll();
        } catch (SchedulerException e) {
            log.error("获取Scheduler失败 ",e);
            return false;
        }
        return true;
    }

    /**
     * 删除定时任务
     * @param task
     * @return
     */
    public boolean removeTask(QuartzTask task){
        return removeTask(task.getJobName(),task.getJobGroupName());
    }
    /**
     * 删除定时任务
     * @param jobName 定时任务class路径
     * @param jobGroupName 定时任务组名
     * @return
     */
    public boolean removeTask(String jobName,String jobGroupName){
        try {
            JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            log.error("获取Scheduler失败 ",e);
            return false;
        }
        return true;
    }


    /**
     * 更新或添加一个任务
     * @param task
     * @return
     */
    public boolean addOrupdateTask(QuartzTask task){
        return addOrupdateTask(task.getJobName(),task.getJobGroupName(),task.getTriggerName(),task.getTriggerGroupName(),
                task.getJobClass(),task.getCron(),task.getParams());
    }
    /**
     * 更新或添加一个任务
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     * @param jobClass
     * @param cron
     * @param params
     * @return
     */
    public boolean addOrupdateTask(
            String jobName,
            String jobGroupName,
            String triggerName,
            String triggerGroupName,
            String jobClass,
            String cron,
            Map<String, Object> params){
        try {
            JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            //已存在
            if(trigger!=null){
                // trigger已存在，则更新相应的定时设置
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
                // 按新的cronExpression表达式重新构建trigger
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
                // 按新的trigger重新设置job执行
                scheduler.rescheduleJob(triggerKey, trigger);
            }else{
                addJob(jobName,jobGroupName,triggerName,triggerGroupName,jobClass,cron,params);
            }
        } catch (SchedulerException e) {
            log.error(">>>>>>>>>> {}",e);
            return false;
        } catch (Exception e1) {
            log.error(">>>>>>>>>> {}",e1);
            return false;
        }
        return true;
    }
}
